document.addEventListener('DOMContentLoaded', function() {
  const activityUrlInput = document.getElementById('activityUrl');
  const minPriceInput = document.getElementById('minPrice');
  const startBtn = document.getElementById('startBtn');
  const statusDiv = document.getElementById('status');
  const mallNameSpan = document.getElementById('mallName');
  const mallIdSpan = document.getElementById('mallId');


  // 初始禁用开始报名按钮
  startBtn.disabled = true;

 
// 自动获取店铺信息
function getShopInfo() {
    startBtn.disabled = true;
    statusDiv.textContent = '正在获取店铺信息...';
      // 添加超时处理
   
    // 先尝试直接获取店铺信息，如果已经有了就不需要刷新页面
    chrome.runtime.sendMessage({action: 'getShopInfo'}, (response) => {
      
      console.log('getShopInfo响应:', JSON.stringify(response));
      if (response && response.success && response.shopInfo) {
        console.log('已经获取到店铺信息，直接显示');
        // 已经有店铺信息，直接显示
        mallNameSpan.textContent = response.shopInfo.mallName || '-';
        mallIdSpan.textContent = response.shopInfo.mallId || '-';
        document.getElementById('registrationForm').style.display = 'block';
        startBtn.disabled = false;
        statusDiv.textContent = '店铺信息获取成功';
      } else {
        console.log('没有获取到店铺信息，尝试刷新页面');
        // 没有店铺信息，需要刷新页面触发网络请求
        tryRefreshAndGetInfo();
      }
    });
}

  // 页面加载完成后自动获取店铺信息
  getShopInfo();
  
  // 尝试刷新页面并获取信息的函数
function tryRefreshAndGetInfo() {
  // 没有店铺信息，需要刷新页面触发网络请求
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    if (tabs && tabs.length > 0 && tabs[0]) {
      chrome.tabs.reload(tabs[0].id);
      setTimeout(async () => {
        try {
          // 设置超时时间为10秒
          const timeoutPromise = new Promise((_, reject) => {
            setTimeout(() => reject(new Error('获取店铺信息超时')), 30000);
          });
          
          const responsePromise = new Promise((resolve) => {
            chrome.runtime.sendMessage({action: 'getShopInfo'}, (response) => {
              if (chrome.runtime.lastError) {
                console.error('获取店铺信息错误:', chrome.runtime.lastError);
                resolve({ success: false, error: chrome.runtime.lastError.message });
              } else {
                resolve(response);
              }
            });
          });
          
          // 使用Promise.race来处理超时
          const response = await Promise.race([responsePromise, timeoutPromise]);
          console.log("获取店铺信息响应:", JSON.stringify(response));
          
          if (response && response.success) {
            mallNameSpan.textContent = response.shopInfo.mallName || '-';
            mallIdSpan.textContent = response.shopInfo.mallId || '-';
            document.getElementById('registrationForm').style.display = 'block';
            startBtn.disabled = false;
            statusDiv.textContent = '店铺信息获取成功';
          } else {
            throw new Error(response?.error || '获取店铺信息失败');
          }
        } catch (error) {
          console.error('获取店铺信息失败:', error);
          mallNameSpan.textContent = '-';
          mallIdSpan.textContent = '-';
          statusDiv.textContent = `错误：${error.message}`;
          startBtn.disabled = true;
        }
      }, 2000); // 增加延迟时间，确保网络请求有足够时间触发
    } else {
      statusDiv.textContent = '错误：未找到活动标签页';
    }
  });
}

  
  // 刷新按钮点击事件


  // 监听店铺信息更新
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'updateShopInfo' && request.shopInfo) {
      mallNameSpan.textContent = request.shopInfo.mallName || '-';
      mallIdSpan.textContent = request.shopInfo.mallId || '-';
      document.getElementById('registrationForm').style.display = 'block';
      startBtn.disabled = false;
    } else if (request.action === 'registrationStatus') {
      const { success, total, failed } = request;
      statusDiv.textContent = `报名完成！成功：${total - failed}，失败：${failed}`;
    }
    // 确保返回true以保持消息通道开放
    return true;
  });

  startBtn.addEventListener('click', async function() {
    console.log('开始按钮点击');
    const url = activityUrlInput.value.trim();
    if (!url) {
      statusDiv.textContent = '请输入活动报名链接';
      return;
    }
    if(!minPriceInput.value){
      statusDiv.textContent = '请输入不报名的最低参考申报价格';
      return;
    }

    try {
      statusDiv.textContent = '正在解析活动链接...';
      const minPrice = parseFloat(minPriceInput.value) || 500;
      // 发送消息给后台脚本
      const response = await new Promise((resolve) => {
          chrome.runtime.sendMessage({
            action: 'startRegistration',
            activityUrl: url,
            minPrice: minPrice
          }, (response) => {
            if (chrome.runtime.lastError) {
              resolve({ success: false, error: chrome.runtime.lastError.message });
            } else {
              resolve(response);
            }
          });
      });

      if (response.success) {
        console.log(response)
        statusDiv.textContent = '报名流程已启动，请等待...';
      } else {
        statusDiv.textContent = `错误：${response.error}`;
      }
    } catch (error) {
      statusDiv.textContent = `发生错误：${error.message}`;
    }
  });
});